<?php

// leetcode503题，下一个更大的元素2

class Solution {

    function nextGreaterElements($nums) {
        $n = count($nums);
        $res = array_fill(0, $n, -1);
        $deque = new SplStack();
        for ($i = 0; $i < $n * 2; ++$i) {
            while (!$deque->isEmpty() && $nums[$i % $n] > $nums[$deque->top()]) {
                $res[$deque->pop()] = $nums[$i % $n];
            }
            $deque->push($i % $n); // 0, 1,
        }
        return $res;
    }

}

$arr = [1,2,1];
$solution = new Solution();
$res = $solution->nextGreaterElements($arr);
print_r($res);